﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace Red.Controls.Converters
{
    public enum HumanReadableParam
    {
        Kilobytes,
        Megabytes,
        Gigabytes,
    }

    public sealed class BytesToHumanReadableConverter : IValueConverter
    {
        public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
        {
            ulong bytes = (ulong)value;

            HumanReadableParam? mode = parameter as HumanReadableParam?;

            if( mode == null )
            {
                mode = HumanReadableParam.Megabytes;
            }

            double readable;
            string suffix;

            switch( mode )
            {
                case HumanReadableParam.Kilobytes:
                    readable = bytes;
                    suffix = "KB";
                    break;

                case HumanReadableParam.Megabytes:
                    readable = bytes >> 10;
                    suffix = "MB";
                    break;

                case HumanReadableParam.Gigabytes:
                    readable = bytes >> 20;
                    suffix = "GB";
                    break;

                default:
                    return $"{bytes}B";
            }

            // Each format is set "off by one" (megabytes, readable = kilobytes)
            // Then we divide here one final time to get the fractional value
            readable /= 1024;
            return $"{readable:N2}{suffix}";

        }

        public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
        {
            throw new NotImplementedException();
        }
    }
}
